<?php

Class QuestionOption extends CI_Model {
    
    function getAll() {
        $this->db->select('*');
        $this->db->from('q_options');       
        //$this->db->order_by("id", "asc");
        
        $query = $this->db->get();

        if ($query->num_rows() >= 1) {
            return $query->result_array();
        } else {
            return false;
        }
    }
    
    function get($id) {
        $query = $this->db->get_where('q_options', array('id' => $id));
        return $query->row_array();
    }

    function delete($id) {
        $this->db->delete('q_options', array('id' => $id));
        return "Đã xóa!";
    }

    function insert($newRecord) {
        if ($this->db->insert('q_options', $newRecord)) {
            return "Đã thêm!";
        } else {
            return "Unable to add";
        }
    }
    
    function update($newRecord)
    {
        $this->db->where('id', $newRecord['id']);
        $this->db->update('q_options', $newRecord);
        return "Đã cập nhật!";
    }
    
    function get_by_question($questionId) {
        $query = $this->db->get_where('q_options', array('qid' => $questionId));
        if ($query->num_rows() >= 1) {
            return $query->result_array();
        } else {
            return false;
        }
    }
    
    function get_number_of_selected($questionId, $optionId, $evaluationId)
    {
        //$queryString = "select count(*) as 'Number' from `quiz_result` where `oids` like '%$optionId%' and `quid` in (SELECT `quid` FROM `quiz` WHERE `eid` = $evaluationId)";
        $queryString = "select count(*) as 'Number' from `quiz_result` where `oids` like '$optionId,%' and `quid` in (SELECT `quid` FROM `quiz` WHERE `eid` = $evaluationId)";
        
        $query = $this->db->query($queryString);
        $result = $query->row_array();
        
        $queryString2 = "select count(*) as 'Number' from `quiz_result` where `oids` like '%,$optionId,%' and `quid` in (SELECT `quid` FROM `quiz` WHERE `eid` = $evaluationId)";
        $query2 = $this->db->query($queryString2);
        $result2 = $query2->row_array();
        
        $queryString3 = "select count(*) as 'Number' from `quiz_result` where `oids` like '%,$optionId' and `quid` in (SELECT `quid` FROM `quiz` WHERE `eid` = $evaluationId)";
        $query3 = $this->db->query($queryString3);
        $result3 = $query3->row_array();
        
        return $result['Number'] + $result2['Number'] + $result3['Number'];
    }

}
